import paramiko

# 跳板机信息
BASTION_HOST = "192.168.100.113"
BASTION_USER = "u"
BASTION_PASSWORD = "1"

# 太空服务器信息
SPACE_SERVER = "192.168.201.103"
SPACE_USER = "user"
SPACE_PASSWORD = "user"

# 远程日志目录
LOG_DIR = "/home/user/output/16/"
LOG_FILE = "model_run.log"  # 日志文件名

def get_logs_through_bastion():
    try:
        # 1. 连接跳板机
        bastion_client = paramiko.SSHClient()
        bastion_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        bastion_client.connect(BASTION_HOST, username=BASTION_USER, password=BASTION_PASSWORD)

        # 2. 通过跳板机连接太空服务器
        transport = bastion_client.get_transport()
        dest_addr = (SPACE_SERVER, 22)
        local_addr = (BASTION_HOST, 22)
        bastion_channel = transport.open_channel("direct-tcpip", dest_addr, local_addr)

        space_client = paramiko.SSHClient()
        space_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        space_client.connect(SPACE_SERVER, username=SPACE_USER, password=SPACE_PASSWORD, sock=bastion_channel)

        # 3. 读取日志文件
        cmd = f"tail -f {LOG_DIR}{LOG_FILE}"  # 监听日志实时更新
        stdin, stdout, stderr = space_client.exec_command(cmd)

        print("📡 正在获取太空服务器日志...")
        for line in iter(stdout.readline, ""):
            print(line.strip())  # 实时打印日志到本地终端

    except Exception as e:
        print(f"❌ 连接失败: {e}")
    finally:
        if bastion_client:
            bastion_client.close()
        if space_client:
            space_client.close()

if __name__ == "__main__":
    get_logs_through_bastion()
